package com.black.common.auth.interceptor;

import com.black.common.auth.UserContextHolder;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义权限拦截器
 * 进行当前请求设置用户信息
 * 往线程请求线程ThreadLocal设值
 * @author linwenfeng
 */
@Component
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, @Nullable HttpServletResponse response, @Nullable Object handler) {
        Map<String, String> loginUser = new HashMap<>(4,1);
        loginUser.put("userId", request.getHeader("x-user-id"));
        loginUser.put("username", request.getHeader("x-user-name"));
        loginUser.put("comCode", request.getHeader("x-com-code"));
        loginUser.put("iconUrl", request.getHeader("x-icon-url"));
        UserContextHolder.setContext(loginUser);
        return true;
    }

    @Override
    public void afterCompletion(@Nullable HttpServletRequest request, @Nullable HttpServletResponse response, @Nullable Object handler, @Nullable Exception ex) {
        UserContextHolder.shutdown();
    }

}
